package order

import (
	"context"
	"fmt"

	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
	"oil-station-backend/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type CompleteOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCompleteOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CompleteOrderLogic {
	return &CompleteOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CompleteOrderLogic) CompleteOrder(req *types.CompleteOrderReq) (resp *types.Order, err error) {
	// 从上下文中获取用户ID和角色
	userId, role, err := l.getUserInfoFromContext()
	if err != nil {
		return nil, err
	}

	// 获取订单详情
	order, err := l.svcCtx.OrderModel.FindById(req.OrderId)
	if err != nil {
		return nil, fmt.Errorf("订单不存在")
	}

	// 检查权限：只有管理员或订单所有者可以完成订单
	if role != "admin" && order.UserId != userId {
		return nil, fmt.Errorf("无权操作此订单")
	}

	// 检查订单状态
	if order.Status == "completed" {
		return nil, fmt.Errorf("订单已完成，不能重复操作")
	}
	if order.Status == "cancelled" {
		return nil, fmt.Errorf("订单已取消，不能完成")
	}

	// 完成订单
	updatedOrder, err := l.svcCtx.OrderModel.Complete(req.OrderId, req.ActualVolume, req.ActualAmount)
	if err != nil {
		return nil, err
	}

	// 更新库存（实际应用中应该在事务中处理）
	// 这里简化处理，直接减少库存
	inventories, err := l.svcCtx.InventoryModel.FindAll()
	if err == nil {
		for _, inv := range inventories {
			if inv.FuelType == updatedOrder.FuelType {
				// 减少库存
				l.svcCtx.InventoryModel.UpdateStock(inv.Id, inv.Stock-req.ActualVolume)
				break
			}
		}
	}

	// 转换为API响应格式
	var completeTime string
	if updatedOrder.CompleteTime != nil {
		completeTime = updatedOrder.CompleteTime.Format("2006-01-02 15:04:05")
	}

	var actualVolume, actualAmount float64
	if updatedOrder.ActualVolume != nil {
		actualVolume = *updatedOrder.ActualVolume
	}
	if updatedOrder.ActualAmount != nil {
		actualAmount = *updatedOrder.ActualAmount
	}

	return &types.Order{
		Id:            updatedOrder.Id,
		OrderNo:       updatedOrder.OrderNo,
		UserId:        updatedOrder.UserId,
		UserName:      updatedOrder.UserName,
		FuelType:      updatedOrder.FuelType,
		FuelPrice:     updatedOrder.FuelPrice,
		Volume:        updatedOrder.Volume,
		PrepaidAmount: updatedOrder.PrepaidAmount,
		ActualVolume:  actualVolume,
		ActualAmount:  actualAmount,
		Status:        updatedOrder.Status,
		CreateTime:    updatedOrder.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    updatedOrder.UpdateTime.Format("2006-01-02 15:04:05"),
		CompleteTime:  completeTime,
	}, nil
}

func (l *CompleteOrderLogic) getUserInfoFromContext() (int64, string, error) {
	// 使用通用工具函数获取用户信息
	return utils.GetUserInfoFromContext(l.ctx)
}